<?php

	include("Commons.php");
$ads_index = array(2, 8);
$newlimit = 90;

	// loginRequired( getTerm('search', 'search_for_a_penpal') );
	
	$action = param('ac');
	
	if ( $action=='search' )
	{
		$where = array();
		
		$search_parameters = array();
		
		$bias1 = param('bias1');
		$bias2 = param('bias2');	
		$country = param('country');
		$continent = param('continent');
		$gender = param('gender');
		$photo = param('photo');
		
		if ( is_numeric($bias1) && is_numeric($bias2) )
		{
			if ( $bias2<$bias1 )
			{
				$temp = $bias1;
				$bias1 = $bias2;
				$bias2 = $temp;
			}
	
			array_push($where, "birthday BETWEEN (CURDATE()-INTERVAL '$bias2' YEAR) AND (CURDATE()-INTERVAL '$bias1' YEAR)");
			
			array_push($search_parameters, "2,$bias1");
			array_push($search_parameters, "3,$bias2");
		}
		elseif ( is_numeric($bias1) )
		{
			array_push($where, "birthday<(CURDATE()-INTERVAL ('$bias1') YEAR)");
			array_push($search_parameters, "2,$bias1");
		}
		elseif ( is_numeric($bias2) )
		{
			array_push($where, "birthday>(CURDATE()-INTERVAL ('$bias2'+1) YEAR)");
			array_push($search_parameters, "3,$bias2");
		}
		elseif ( !empty($bias1) || !empty($bias2) )
			$ageerror = getTerm('search', 'invalid_age');
	
		
		if ( empty($country) )
		{}
		elseif ( !is_numeric($country) )
			$countryerror = getTerm('search', 'empty_country');
	
		else
		{
			$rh = query("SELECT id FROM region WHERE id='$country' AND is_country=1;");
			if ( mysql_num_rows($rh)!=1 )
				$countryerror = getTerm('search', 'empty_country');
	
			else
			{
				if ( isIdentified() )
					array_push($where, "country='$country'");
				array_push($search_parameters, "1,$country");
			}
		}
			
		if ( !in_array($gender, array('female', 'male') ) && ! empty($gender) )
			$gendererror = getTerm('search', 'empty_gender');
	
		elseif ( !empty($gender) )
		{
			array_push($where, "gender='$gender'");
			array_push($search_parameters, "4,". ($gender=='male'?1:2) );
		}
			

		if ( !empty($continent)  && is_numeric($continent)) {
			$rh = query("SELECT id FROM region WHERE parent IN (SELECT id FROM region WHERE parent IN ((SELECT id FROM region WHERE id = $continent)));");
			if ( mysql_num_rows($rh)>0 ) {
				$ids = array();
				while ($row = mysql_fetch_array($rh)) {
					array_push($ids, $row[0]);
				}
				$allids = implode(',', $ids);
				array_push($where, "p.country IN ($allids)");
			}
		}
		if ($photo == 'on') {
			array_push($where, "ph.type <> '' AND ph.id IS NOT NULL");
		}


		$page = param('page');
		if ( empty($page) || !is_numeric($page) )
			$page=1;
			
		$order = param('order');
		if ( empty($order) || !is_numeric($order) )
			$order=1;

		if ( !empty($ageerror) || !empty($countryerror) || !empty($gendererror) )
			$action = '';
			
		// Search storage for further purposes
		$parameters = array();
		foreach ( $_GET as $key=>$value )
		
			if ( !empty($value) )
			
				array_push($parameters, "$key=$value");
				
		sort($parameters);
	
		$newurl = formatUrl( '/search/?'. implode($parameters, '&') );
				
		if ( $newurl!=$_SERVER['REQUEST_URI'] )
		{
			// Storage of parameters
			query("INSERT INTO search (user,searchdate) VALUES (${_SESSION[user]},NOW());");
			$sid = mysql_insert_id();
			foreach ( $search_parameters as $sp )
				query("INSERT INTO searchparameters (search,parameter,value) VALUES ($sid,$sp);");
				
			header("Location: $newurl");
			
			exit();
		}
		else
			$_SESSION['url'] = $parameters;
			
		$_SESSION['browser'] = 'search';
			
	}
	
	
	if ( $action=='search' )
	{
		if ( count($where)==0 )
			array_push($where, '1');
			
		pushNavigationItem( getTerm('search', 'search_for_a_penpal'), '/search/' );
		pushNavigationItem( getTerm('search', 'search_results'), '/search/' );
		
		printHeader( getTerm('base', 'site_name') , getTerm('search', 'search_results'), 'search' );

		
		$itemsPerPage = getConfiguration('application', 'itemsPerPage');


		if ($order == 2) {
			$moreleft = 'LEFT JOIN event ev ON ev.user = u.id AND ev.event_type = 2';
			$sort = 'GROUP BY p.user ORDER BY coalesce(max(ev.date),u.since) DESC';
		} else {
			$moreleft = '';
			$sort = 'ORDER BY u.id DESC';
		}

		$sql = "SELECT u.username, TIMESTAMPDIFF(DAY,u.since,NOW()) as uage, YEAR(CURDATE()) - YEAR(p.birthday) - IF( RIGHT(CURDATE(),5) < RIGHT(p.birthday,5) , 1, 0 ) AS 'age', p.gender, p.description, c.name AS 'country', ph.id, ph.type
				FROM user u
				JOIN profile p ON p.user=u.id AND p.current=1
				JOIN region c ON p.country=c.id
				LEFT JOIN photo ph ON ph.id=p.photo
				$moreleft
				WHERE ". implode(' AND ', $where) ."
				AND u.banned=0
				$sort;";

#		print "$sql<br>";
		$rh = query($sql);
		$rows = mysql_num_rows($rh);

		$self = str_replace("&page=$page", "", $newurl);

		$numofpages = ceil($rows / $itemsPerPage); 
		$page_num = $page;
		$pagin = paginator($page_num, $numofpages, $self);
		print fill( getTerm('search_new', 'profiles_found') , $rows);
		print "<form action=\"${_SERVER[REQUEST_URI]}\" method=\"get\" name=\"search_form\"><input type=\"hidden\" name=\"ac\" value=\"search\" /><input type=\"hidden\" name=\"page\" value=\"1\" /><br>";
		print getTerm('search_new','sort_by').'&nbsp;<select name="order" id="order" onchange="document.search_form.submit();">';
		print "<option value=\"1\">". getTerm('search_new','registration_date') ."</option>";
		$sel = ($order == 2) ? 'selected' : '';
		print "<option value=\"2\"$sel>". getTerm('search_new','last_login') ."</option>";
		print '</select>';


		echo $pagin;

		
		if ( $country!= 0 && ! isIdentified() )
			print '<p><div class="warning"><div class="warning-hint">'. fill( getTerm('search','country_disabled_for_search') , formatUrl('/signin')) .'</div></div></p>';
		
		if ( $rows>0 )
		{
			print '<div id="profile-list" class="box">';
			
			mysql_data_seek($rh, ($page-1)*$itemsPerPage );
			
			$currentItem = 0;
			
			while ( ($currentUser = mysql_fetch_array($rh)) && $currentItem<$itemsPerPage)
			{




				$profileurl = formatUrl("/profile/${currentUser[username]}");
				print '<div class="profile">';
				if ($currentUser['uage'] < $newlimit) {
					echo "NEW!";
				}
			
				if ( !empty($currentUser['type']) )
					print '<img class="photo" src="/Thumbs/'. $currentUser['id'] .'-small.'. strtolower($currentUser['type']) .'" />';

	


				print '<div class="username"><a href="'. $profileurl .'">'. $currentUser['username'] .'</a></div>';
				print '<div class="overview">'. fill( getTerm('profile', 'user_overview'), $currentUser['age'], getTerm('profile', $currentUser['gender']), getTerm('country', $currentUser['country']) ) .'</div>';
				print '<div class="description">'. wrapString( $currentUser['description'], 50, '...') .'</div>';
				print '<div class="to-profile"><a href="'. $profileurl .'">'. fill( getTerm('search','see_member_profile'), $currentUser['username'] ) .'</a></div>';
				print '</div>';
				
				$currentItem++;
				if (in_array($currentItem, $ads_index)) {
					print '<div class="profile">';
					showad();
					print '</div>';
				}

			}


			
			mysql_free_result($rh);
			showad();
			echo $pagin;			
			print '</div>';
		}
		else
		{
			print '<div class="box"><p>'. getTerm('search', 'no_result') .'</p></div>';
		}
		


		print '<div id="search-form" class="box">';
		print '<h2>'. getTerm('search', 'modify_search') .'</h2>';
		print '<p>'. getTerm('search', 'modify_criterias') .'</p>';
		
	}
	else
	{
		pushNavigationItem( getTerm('search', 'search_for_a_penpal'), '/search/' );
	
		printHeader( getTerm('search', 'search_for_a_penpal') , getTerm('search', 'search_for_a_penpal'), 'search' );
		print '<div id="search-form" class="box"><p>'. getTerm('search', 'indicate_criterias') .'</p>';
		print "<form action=\"${_SERVER[REQUEST_URI]}\" method=\"get\" name=\"search_form\"><input type=\"hidden\" name=\"ac\" value=\"search\" /><input type=\"hidden\" name=\"page\" value=\"1\" />";
	}
	
	$scountry = $country;
	$scontinent = $continent;

	$rh = query('SELECT id,name FROM region WHERE is_country=1 ORDER BY name;');
	
	$countries = array();
	
	while ( $country = mysql_fetch_array($rh) )
		$countries[ getTerm('country', $country[1]) ] = $country[0];
		
	ksort($countries);


	$rh = query('SELECT id,name FROM `region` WHERE parent IS NULL AND is_country = 0;');
	
	$continents = array();
	
	while ( $continent = mysql_fetch_array($rh) )
		$continents[ getTerm('country', $continent[1]) ] = $continent[0];
		
	ksort($continents);


	
	
	if ( ! isIdentified() )
		print '<div class="warning"><div class="warning-hint">'. fill( getTerm('search','country_disabled') , formatUrl('/signin')) .'</div>';
	
	print '<div class="field'. (empty($countryerror) ? '' : ' error') .'"><label for="country">'. getTerm('search', 'his_her_country') .'</label>';
	print (empty($countryerror) ? '' : "<div class=\"error-hint\">$countryerror</div>");
	print '<select name="country" id="country"'. (isIdentified() ? '' : ' disabled="disabled"') .'><option value="">'. getTerm('search','anywhere') .'</option>';
	foreach ( $countries as $country=>$id )
		print "<option value=\"". $id ."\"". ($id==$scountry ? ' selected="selected"' : '') .">". $country ."</option>";
	print '</select></div>';
	
	print '<div class="field'. (empty($continenterror) ? '' : ' error') .'"><label for="continent">'. getTerm('search_new', 'continent') .'</label>';
	print '<select name="continent" id="continent"'. (isIdentified() ? '' : ' disabled="disabled"') .'><option value="">'. getTerm('search','anywhere') .'</option>';
	foreach ( $continents as $continent=>$id )
		print "<option value=\"". $id ."\"". ($id==$scontinent ? ' selected="selected"' : '') .">". $continent ."</option>";
	print '</select></div>';

	if ( ! isIdentified() )
		print '</div>';
	
	
	print '<div class="field'. (empty($ageerror) ? '' : ' error') .'"><label for="bias1">'. getTerm('search', 'his_her_age') .'</label>';
	print (empty($ageerror) ? '' : "<div class=\"error-hint\">$ageerror</div>");

	$biasselect1 = '<select name="bias1" id="bias1"><option value="" />'. getTerm('search', 'any') .'</option>';
	$biasselect2 = '<select name="bias2" id="bias2"><option value="" />'. getTerm('search', 'any') .'</option>';
	for ( $i=1 ; $i<100 ; $i++ )
	{
		$biasselect1 .= "<option value=\"$i\"". ($i==$bias1 ? ' selected="selected"' : '') .">$i</option>";
		$biasselect2 .= "<option value=\"$i\"". ($i==$bias2 ? ' selected="selected"' : '') .">$i</option>";
	}
	$biasselect1 .= '</select>';
	$biasselect2 .= '</select>';
	
	print fill( getTerm('search', 'between_and') , $biasselect1, $biasselect2 );
	print '</div>';
	
	
	print '<div class="field'. (empty($gendererror) ? '' : ' error') .'"><label for="gender">'. getTerm('search', 'his_her_gender') .'</label>';
	print (empty($gendererror) ? '' : "<div class=\"error-hint\">$gendererror</div>");
	print '<select name="gender" id="gender">';
	print "<option value=\"\">". getTerm('search','either') ."</option>";
	foreach ( array('female','male') as $gende )
		print "<option value=\"". $gende ."\"". ($gende==$gender ? ' selected="selected"' : '') .">". getTerm('profile', $gende) ."</option>";
	print '</select></div>';


	print '<div class="field">';
	print '<input type="checkbox" name="photo"'.($photo == 'on' ? 'checked' : '').'>'. getTerm('search_new', 'photo_only');
	print '</div>';
	print "<div class=\"field\"><input type=\"submit\" value=\"" . getTerm('search', 'find_a_penpal') . "\" /></div>";

	
	print "</form></div>";

	printFooter();


function paginator($page_num, $numofpages, $self) {
	if ( $numofpages > 1 ) {
		$range =10; 
		$range_min = ($range % 2 == 0) ? ($range / 2) - 1 : ($range - 1) / 2; 
		$range_max = ($range % 2 == 0) ? $range_min + 1 : $range_min; 
		$page_min = $page_num- $range_min; 
		$page_max = $page_num+ $range_max; 
		$page_min = ($page_min < 1) ? 1 : $page_min; 
		$page_max = ($page_max < ($page_min + $range - 1)) ? $page_min + $range - 1 : $page_max; 

		if ($page_max > $numofpages) { 
			$page_min = ($page_min > 1) ? $numofpages - $range + 1 : 1; 
			$page_max = $numofpages; 
		} 

		$page_min = ($page_min < 1) ? 1 : $page_min; 


		if ( ($page_num > ($range - $range_min)) && ($numofpages > $range) ) { 
			$page_pagination .= '<a title="'.getTerm('search', 'first').'" href="'.$self.'&page=1">'.getTerm('search', 'first').'</a> '; 
		} 

		if ($page_num != 1) { 
			$page_pagination .= '<a href="'.$self.'&page='.($page_num-1). '">'.getTerm('search', 'previous').'</a> '; 
		} 

		for ($i = $page_min;$i <= $page_max;$i++) { 
			if ($i == $page_num) {
				$page_pagination .= '<strong>' . $i . '</strong> '; 
			} else {
				$page_pagination.= '<a style="border:solid 1px #DEDEDE; color:#888888; float:center; font-weight:bold; margin-right:2px; padding:3px 4px;" href="'.$self.'&page='.$i. '">'.$i.'</a> '; 
			}
		} 

		if ($page_num < $numofpages) { 
			$page_pagination.= ' <a href="'.$self.'&page='.($page_num + 1) . '">'.getTerm('search', 'next').'</a>'; 
		}

		if (($page_num< ($numofpages - $range_max)) && ($numofpages > $range)) { 
			$page_pagination .= ' <a title="'.getTerm('search', 'last').'" href="'.$self.'&page='.$numofpages. '">'.getTerm('search', 'last').'</a> '; 
		} 
		return '<p class="page-links">'.$page_pagination.'</p>';
	}
}


function showad() {
print 'ad placeholder';
return;
print '<script type="text/javascript"><!--
google_ad_client = "pub-2652372001711469";
/* home-bottom */
google_ad_slot = "6307905656";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>';
}	


?>